package com.atguigu.gmall.exception;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 卡尼奶
 * @Date 2022/5/20 14:36
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 定义自定义异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(GmallException.class)
    public Result gmallException(GmallException e){
        log.error("全局异常处理：{}",e);
        Result fail = Result.fail();
        fail.setCode(e.getCode());
        fail.setMessage(e.getMessage());
        return fail;
    }


    /**
     * 定义全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result globalException(Exception e){
        log.error("全局异常处理-系统异常：{}",e);
        Result fail = Result.fail();
        fail.setCode(500);
        fail.setMessage("服务器系统异常");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        StringBuffer url = request.getRequestURL();
        Map<String, String[]> params = request.getParameterMap();
        Map<String ,Object> map = new HashMap<>();
        map.put("url",url);
        map.put("params",params);
        fail.setData(map);
        return fail;
    }
}
